/*
    jME Terra package. A Terrain Engine for the Java Monkey Engine.
    Copyright (C) 2005-2006,  Tijl Houtbeckers
    
    **** LICENSE: ****

	This library is free software; you can redistribute it and/or
	modify it under the terms of the GNU Lesser General Public
	License as published by the Free Software Foundation,
	version 2.1.
	
	This library is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
	Lesser General Public License for more details.
	
	You should have received a copy of the GNU Lesser General Public
	License along with this library; if not, write to the Free Software
	Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA

	**** CONTACT: ****

    I can be reached through the jmonkeyengine.com forums (user "llama"), 
    or the jmonkeyengine.com contact page:
    jmonkeyengine.com/index.php?option=com_contact&task=view&contact_id=5           

*/

/**
 * @author Tijl Houtbeckers
 */

package org.llama.jmex.terra.pass;

import org.llama.jmex.terra.TerraView;
import org.llama.jmex.terra.XYKey;

public abstract class DistancePass extends TerraViewPass {
	
	private long distancesq;
	private long distancesqe;
	protected boolean block;
	
	public DistancePass(int distance, String key, boolean block) {
		setDistance(distance);
		this.block = block;
		this.setKeyFilter(key);
		
	}
	
	public void setDistance(int distance) {
		this.distancesq = distance * distance;
		this.distancesqe = (long) (distancesq * 1.05);	
	}
	
	public void addToView(TerraView tv) {
		tv.addPass(this, 0, TerraView.PASS_CURRENT);
		if (block)
			tv.addPass(this, 0, TerraView.PASS_BLOCK);
		else
			tv.addPass(this, 0, TerraView.PASS_MAP);

	}

	public abstract void remove(XYKey xy, final TerraView tv);
	public abstract void add(XYKey xy, final TerraView tv);
	private int cornercount = 0;
	
	
	public boolean pass(XYKey xy, TerraView tv, String passtype, int pass) {
		long compare = block 
				? tv.getTerraManager().distanceToBlockSquared(xy.x, xy.y, tv.lastx, tv.lasty) 
				: tv.getTerraManager().distanceToMapSquared(xy.x, xy.y, tv.lastx, tv.lasty);
		
		if (compare > distancesqe) {

			if (passtype.equals(TerraView.PASS_CURRENT)) {
				remove(xy, tv);
			} else return false;
		}
		else if (passtype.equals(TerraView.PASS_BLOCK) || passtype.equals(TerraView.PASS_MAP)) { 
			if (compare <= distancesq) {
				add(xy, tv);
			} else if ((xy.x == tv.startx || xy.y == tv.starty) && ++cornercount == 4) {
				cornercount=0;
				return false;
			}
		}
		else return false;
		return true;
	}
	


}
